import { Injectable } from '@nestjs/common';
import { VoteModelService } from 'src/models/vote-model/vote-model.service';
import { VoteOptionModelService } from 'src/models/vote-option-model/vote-option-model.service';
import { errorReturn, successReturn } from 'src/utils';
const crypto = require('crypto');
var moment = require('moment');
const fs = require('fs');

@Injectable()
export class PublishService {
    constructor(private voteModelService:VoteModelService, private voteOptionModelService:VoteOptionModelService){}
    async upload(file){
        const ext = file.originalname.split('.').pop()
        let day = moment().format('YYYYMMDD')
        let saveFileName = day + '/' + crypto.createHash('md5').update(moment().valueOf() + file.originalname).digest('hex').toLowerCase()+ '.' + ext
        let dir = '/home/wwwroot/vote/uploads/'
        try {
            fs.statSync(dir + day)
        } catch (error) {
            fs.mkdirSync(dir + day, {recursive : true})
        }

        try {
            await fs.promises.writeFile(dir + saveFileName, file.buffer)
        } catch (error) {
            return errorReturn(error.message)
        }
        
        return successReturn(saveFileName)

    }

    async publish(params) {
        let id = await this.voteModelService.insert({content : params.content, vote_type : params.type, user_id : 1, expire_in : moment(params.expireIn).unix(), create_time : moment().unix()})
        if(id == null) return errorReturn('发布失败')

        let options = params.options.map(option => ({vote_id : id, image : option.image, text : option.text}))
        this.voteOptionModelService.insert(options)
        
        return successReturn(id)
    }
}
